<template>
  <div class="app-role">
    <h3>首页专题管理</h3>
   <!-- <Query
     :items="queryColumns"
     :initial-params="queryParams"
     @query="handleQuery"
     labelWidth="100px"
   /> -->
   <Table
     :table-columns="tableColumns"
     :table-loading="tableLoading"
     :table-data="tableData"
     :total="total"
     @pagination="handlePagination"
     :tree-props="{ children: 'children', hasChildren:'hasChildren',icon:'Plus' }"
   >
     <!-- <template v-slot:tools>
       <el-button-group>
         <el-button type="primary" @click="handleAdd">新增</el-button>
       </el-button-group>
     </template> -->
     <template #jumpUrl="{row}">
        <el-button type="primary" link @click="openPage(row.jumpUrl)">{{row.jumpUrl}}</el-button>
      </template>
     <template #img1="{row}">
        <div class="classifyName_box">
          <img v-if="row.oneImg" class="classifyName_img" :src="row.oneImg" />
          <span v-else>-</span>
        </div>
     </template>
     <template #img2="{row}">
        <div class="classifyName_box">
          <img v-if="row.twoImg" class="classifyName_img" :src="row.twoImg" />
          <span v-else>-</span>
        </div>
     </template>
     <template #img3="{row}">
        <div class="classifyName_box">
          <img v-if="row.threeImg" class="classifyName_img" :src="row.threeImg" />
          <span v-else>-</span>
        </div>
     </template>
     <template #img4="{row}">
        <div class="classifyName_box">
          <img v-if="row.fourImg" class="classifyName_img" :src="row.fourImg" />
          <span v-else>-</span>
        </div>
     </template>
     <template #opt="scope">
       <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
     </template>
   </Table>
   <el-dialog v-model="showDialog" :title="dialogTitle" width="1080">
      <el-form ref="refForm" :model="formData" :rules="formRules" size="default" style="padding-top: 20px;">
        <el-row :span="20">
          <el-col :span="12">
            <el-form-item label="第一大图" label-width="100px" >
              <div class="product_wrap">
                <div class="product_box">
                  <div>{{ formData.oneProductName }}</div>
                  <el-button type="primary" size="default" @click="onOpen('oneId')">{{formData.oneId?'更换商品':'选择商品'}}</el-button>
                </div>
                <div class="product_img_box">
                  <ImageUpload
                    v-model="formData.oneImg"
                    :limit="1"
                    listType="picture-card"
                  >
                  </ImageUpload>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第二小图" label-width="100px" >
              <div class="product_wrap">
                <div class="product_box">
                  <div>{{ formData.twoProductName }}</div>
                  <el-button type="primary" size="default" @click="onOpen('twoId')">{{formData.twoId?'更换商品':'选择商品'}}</el-button>
                </div>
                <div class="product_img_box">
                  <ImageUpload
                    v-model="formData.twoImg"
                    :limit="1"
                    listType="picture-card"
                  >
                  </ImageUpload>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <div style="border-bottom: 1px solid #cecece; width: 100%; margin-bottom: 20px;"></div>
          <el-col :span="12">
            <el-form-item label="第三小图" label-width="100px" >
              <div class="product_wrap">
                <div class="product_box">
                  <div>{{ formData.threeProductName }}</div>
                  <el-button type="primary" size="default" @click="onOpen('threeId')">{{formData.threeId?'更换商品':'选择商品'}}</el-button>
                </div>
                <div class="product_img_box">
                  <ImageUpload
                    v-model="formData.threeImg"
                    :limit="1"
                    listType="picture-card"
                  >
                  </ImageUpload>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第四小图" label-width="100px" >
              <div class="product_wrap">
                <div class="product_box">
                  <div>{{ formData.fourProductName }}</div>
                  <el-button type="primary" size="default" @click="onOpen('fourId')">{{formData.fourId?'更换商品':'选择商品'}}</el-button>
                </div>
                <div class="product_img_box">
                  <ImageUpload
                    v-model="formData.fourImg"
                    :limit="1"
                    listType="picture-card"
                  >
                  </ImageUpload>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <div style="border-bottom: 1px solid #cecece; width: 100%; margin-bottom: 20px;"></div>
          <el-col :span="20">
            <el-form-item label="其他商品" label-width="100px" >
              <div class="product_wrap">
                <div>
                  <div v-if="formData.prodList && formData.prodList.length>0">
                    <span v-for="(item,i) in formData.prodList" :key="'prodList_'+i">
                      {{ item.productName }}
                      <span v-if="formData.prodList.length-1>i">，</span>
                    </span>
                  </div>
                  <el-button type="primary" size="default" @click="onOpen('other')">{{formData.prodList && formData.prodList.length>0?'更换商品':'选择商品'}}</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false" size="default">取消</el-button>
          <el-button type="primary" @click="handleSubmit" size="default">
            确定
          </el-button>
        </div>
      </template>
      <SelectProduct :isCheckbox="isCheckbox" :dialogVisible="dialogVisible" :idsList="productIds" @onOk="onOk" @onClose="dialogVisible = false"></SelectProduct>
    </el-dialog>
  </div>
</template>

<script setup name="productTemeplate">
import Table from "@/components/Table/index.vue";
import SelectProduct from '@/components/SelectProduct'

import Query from "@/components/Query/index.vue";
import DialogForm from '@/components/FormDialog/index.vue'

import { getClassifytree,saveTemplate,saveClassify } from "@/api/goods";
import { getThemeList,saveTheme,getTheme } from "@/api/speciall";
const { proxy } = getCurrentInstance()
const tableData = ref([])
const total = ref(0)
const tableLoading = ref(true)
const dialogTitle = ref('')
const loading = ref(false)
const showDialog = ref(false)
const refForm = ref(false)
const router = useRouter();
const dialogVisible = ref(false)
const productIds = ref([])
const formRules = ref({
  classifyName: [
   { required: true, message: '请输入名称', trigger: 'blur' },
 ],
})
const formData = ref({})
const data = reactive({
 tableColumns: [
  { label: "专题名称", prop: "title",},
   { label: "第一大图", prop: "img1",slot: 'img1'},
   { label: "第二小图", prop: "img2",slot: 'img2' },
   { label: "第三小图", prop: "img3",slot: 'img3' },
   { label: "第四小图", prop: "img4",slot: 'img4' },
   { label: "其他商品名称", prop: "prodNames",width:300 },
   { label: "开始时间", prop: "gmtStart", width:180},
   { label: "结束时间", prop: "gmtEnd", width:180},
   { label: "操作",  prop: "opt", slot: 'opt'},
 ],
 queryColumns: [
 ],
 pageParams: {
  current: 1,
  size: 10
 },
 queryParams: {},
 formItems: [

 ]
})

const { tableColumns, queryColumns, pageParams, queryParams, formItems } = toRefs(data)
/** 获取列表数据 */
const getList = () => {
  tableLoading.value = true
  const data  = {
     ...pageParams.value,
  }
  getThemeList(data)
  .then(res => {
    let list = res.data.records || []
     tableData.value = list
     total.value = res.data.total
  })
  .finally(() => {
     tableLoading.value = false
  })
}

getList()
const allClassList = ref([])
// 获取所有商品分类
const getAllList = () => {
  const data  = {
    current: 1,
    size: 999,
     type:'2',// 1-商品分类
  }
  getClassifytree(data)
  .then(res => {
    allClassList.value = res.data.records
  })
  .finally(() => {
     tableLoading.value = false
  })
}
/** 搜索按钮操作 */
const handleQuery = (val) => {
 queryParams.value = val
 getList()
}
/** 打开新增弹窗 */
const handleAdd = () => {
  dialogTitle.value = '新增专题'
  // 重置表单数据
  formData.value = {
    relationId:'',
    img:''
  }
  showDialog.value = true
  getAllList()
}

/** 打开编辑弹窗 */
const handleEdit = (row) => {
  dialogTitle.value = '专题名称'+row.title
  getTheme({id:row.id}).then(res=>{
      // 重置表单数据
    formData.value = res.data
    showDialog.value = true
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
 proxy.$modal.confirm('是否确认删除此数据？').then(function() {
  saveTemplate({id: row.id, status: -1,type:'2'}).then(() => {
     getList()
     proxy.$modal.msgSuccess("删除成功")
   })
 })
}
const handlePagination = (val) => {
 pageParams.value = val
 getList()
}
const handleSubmit = async () => {
 loading.value = true
 try {
  refForm.value.validate(valid => {
    if (!valid) return
    let params = {
      ...formData.value,
    }
    saveTheme(params).then(res=>{
      showDialog.value = false
      proxy.$modal.msgSuccess("保存成功")
      pageParams.value.current = 1
      getList()
    })
   
  })
   
 } finally {
   loading.value = false
 }
}
const isCheckbox = ref(false)
const openType = ref('')
const onOpen = (type) => {
  let data = formData.value
  let arr = []
  if(type=='other'){
    isCheckbox.value = true
    arr = formData.value.prodList || []
  }else{
    isCheckbox.value = false
    if(type=='oneId'){
      arr=[{
        id:data.oneId,
        productName:data.oneProductName,
      }]
    }
    if(type=='twoId'){
      arr=[{
        id:data.twoId,
        productName:data.twoProductName,
      }]
    }
    if(type=='threeId'){
      arr=[{
        id:data.threeId,
        productName:data.threeProductName,
      }]
    }
    if(type=='fourId'){
      arr=[{
        id:data.fourId,
        productName:data.fourProductName,
      }]
    }
  }
  productIds.value = arr || []
  openType.value = type
  dialogVisible.value = true
}
const onOk = (data) => {
  let type = openType.value
  if(type=='other'){
    let prodArr = JSON.parse(JSON.stringify(formData.value.prodList || []))
    let arr2 = prodArr.filter(item=>item.id)
    let arr = []
    if(arr2.length>0){
      let prodIdList = []
      arr2.map(item => {
        let flag = false
        prodIdList.push(item.prodId)
        data.value.forEach(item2 => {
          if(item2.id==item.prodId){
            flag = true
            item.sortNum = item2.sortNum
          }
        })
        if(flag){
        //   arr.push({
        //     ...item,
        //     delFlag:-1,
        //   })
        // }else{
          arr.push({
            ...item,
            delFlag:0,
          })
        }
      })
      data.value.forEach(item => {
        if(!prodIdList.includes(item.id)){
          arr.push(
            {
              "delFlag": 0,
              "gmtCreate": "",
              "gmtModify": "",
              "id": null,
              "prodId": item.id,
              "sortNum": item.sortNum,
              productName:item.productName
            }
          )
        }
      });
    }else{
      data.value.forEach(item => {
        arr.push(
          {
            "delFlag": 0,
            "gmtCreate": "",
            "gmtModify": "",
            "id": null,
            "prodId": item.id,
            "sortNum": item.sortNum,
            productName:item.productName
          }
        )
      });
    }
    formData.value.prodList = arr
  }else{
    if(type=='oneId'){
      formData.value.oneId = data.value[0]?.id
      formData.value.oneProductName = data.value[0]?.productName
    }
    if(type=='twoId'){
      formData.value.twoId = data.value[0]?.id
      formData.value.twoProductName = data.value[0]?.productName
    }
    if(type=='threeId'){
      formData.value.threeId = data.value[0]?.id
      formData.value.threeProductName = data.value[0]?.productName
    }
    if(type=='fourId'){
      formData.value.fourId = data.value[0]?.id
      formData.value.fourProductName = data.value[0]?.productName
    }
  }
  // formData.value.typeIdList = data.value
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.classifyName_box{
  display: flex;
  align-items: center;
  .classifyName_img{
    width: 60px;
    height: 60px;
    object-fit: contain;
    margin-left: 8px;
  }
  span{

  }
}
.app-role {
 padding: 8px
}
.product_wrap{
  width: 90%;
  display: flex;
  .product_box{
    margin-right: 10px;
    flex: 1;
  }
  .product_img_box{
    width: 200px;
  }
}
</style>